package com.zhang.crowd.mvc.config;

import com.zhang.crowd.entity.Admin;
import com.zhang.crowd.entity.Role;
import com.zhang.crowd.service.api.AdminService;
import com.zhang.crowd.service.api.AuthService;
import com.zhang.crowd.service.api.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

//实现SpringSecurity自带的UserDetailsService接口
@Component
public class CrowdUserDetailsService implements UserDetailsService {
    @Autowired
    AdminService adminService;

    @Autowired
    AuthService authService;

    @Autowired
    RoleService roleService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据账号名称查询admin对象
        Admin admin = adminService.getAdminByLoginAcct(username);
        //获取admin的id
        Integer adminId = admin.getId();
        //根据id查询admin所拥有的角色
        List<Role> assignedRoleList = roleService.getAssignedRole(adminId);
        //根据id查询admin所拥有的权限
        List<String> authNameList = authService.getAssignedAuthNameByAdminId(adminId);

        //创建集合对象用来存储 GrantedAuthority
        List<GrantedAuthority> authorities = new ArrayList<>();

        //遍历assignedRoleList存入角色信息
        for(Role role : assignedRoleList){
            //一定要加上前缀
            String roleName = "ROLE_" + role.getName();

            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(roleName);

            authorities.add(simpleGrantedAuthority);
        }

        //遍历authNameList存入权限信息
        for(String authName : authNameList){

            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(authName);

            authorities.add(simpleGrantedAuthority);

        }
        //封装SecurityAdmin对象
        SecurityAdmin securityAdmin = new SecurityAdmin(admin,authorities);
        return securityAdmin;
    }

}
